
import { _decorator, Component, Node, AudioClip, AudioSource, Prefab, SpriteFrame, JsonAsset, assetManager, AssetManager, Asset } from 'cc';
import { EventMgr } from '../Framework/Managers/EventMgr';
import { ResMgr } from '../Framework/Managers/ResMgr';
import { UIMgr } from '../Framework/Managers/UIMgr';
import { GameLanch } from '../GameLanch';
import { Utils } from '../Framework/Utils/Utils';
import { Globle } from '../Framework/Utils/Globle';

var resPkg = {
    "Sounds": [
        { assetType: AudioClip, 
            urls: []
        },
    ],

    "Json":[
        {
            asserType: JsonAsset,
            urls:[
                "GameURL"
            ]
        }
    ],

    "GUI": [
        {
            assetType: Prefab, 
            urls: [],
            name:"UIPrefabs",
        },
        {
            assetType: SpriteFrame, 
            urls: [],
            name:"GameUI",
        },
    ],
}

export class GameApp extends Component {
    
    public static Instance: GameApp = null as unknown as GameApp
    isLogin:boolean = false;
    isResLoad:boolean = false;

    onLoad(): void {
        if(GameApp.Instance === null) {
            GameApp.Instance = this;
        }
        else {
            this.destroy();
            return;
        }
        assetManager.loadBundle("GUI", (err, bundle: AssetManager.Bundle)=>{
            if(err) {
                console.log("load bundle erro: ", err);
                return;
            }
            for (const iterator of resPkg.GUI) {
                let dataArr = [];
                bundle.getDirWithPath(iterator.name,iterator.assetType,dataArr);
                for (let i = 0; i < dataArr.length; i++) {
                    iterator.urls.push(dataArr[i].path);
                    // console.log(dataArr[i].path);
                }
            }
            this.EnterGame();
        });
        Utils.getUrlAllData();
    }

    // 游戏逻辑入口
    public EnterGame(): void {
        //创建游戏资源加载界面
        UIMgr.Instance.ShowUIPrefab(GameLanch.Instance.UILoading);  
        
        //加载所有游戏资源
        ResMgr.Instance.preloadResPkg(resPkg, (now: any, total: any)=>{
            EventMgr.Instance.Emit("loadProgress", Math.floor(now * 100 / total));
        }, ()=>{
            this.EnterLoadingScene();
        });
    }

    public EnterLoadingScene(): void {
        // 释放UI视图
        UIMgr.Instance.ClearAll();
        UIMgr.Instance.ShowUIView("Home");
        // end

    }

}
